from datetime import datetime
from app import db

class Report(db.Model):
    """测试报告模型"""
    __tablename__ = 'reports'
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    project_id = db.Column(db.Integer, db.ForeignKey('projects.id'), nullable=False)
    total_cases = db.Column(db.Integer, default=0)
    passed_cases = db.Column(db.Integer, default=0)
    failed_cases = db.Column(db.Integer, default=0)
    pass_rate = db.Column(db.String(10), default='0%')
    duration = db.Column(db.String(20), default='')  # 测试执行时长
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    
    # 关系
    test_results = db.relationship('TestResult', backref='report', lazy='dynamic', cascade='all, delete-orphan')
    
    def __repr__(self):
        return f'<Report {self.name}>'
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'name': self.name,
            'project_id': self.project_id,
            'project_name': self.project.name if self.project else '',
            'total_cases': self.total_cases,
            'passed_cases': self.passed_cases,
            'failed_cases': self.failed_cases,
            'pass_rate': self.pass_rate,
            'duration': self.duration,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S')
        }
    
    def save(self):
        """保存到数据库"""
        db.session.add(self)
        db.session.commit()
    
    def delete(self):
        """从数据库删除"""
        db.session.delete(self)
        db.session.commit()
    
    def update_statistics(self):
        """更新统计信息"""
        self.total_cases = self.test_results.count()
        self.passed_cases = self.test_results.filter_by(status='passed').count()
        self.failed_cases = self.test_results.filter_by(status='failed').count()
        
        if self.total_cases > 0:
            self.pass_rate = f"{int(self.passed_cases / self.total_cases * 100)}%"
        else:
            self.pass_rate = "0%"
        
        db.session.commit()